﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Driver;
using System.Collections.Concurrent;

namespace MongoDbWebClient.Common
{
    public class ServersPool
    {
        private static ConcurrentDictionary<string, MongoServer> _servers;
  

        public static string AddServerToWatch(string connectionString)
        {
            if (_servers == null)
	        {
                _servers = new ConcurrentDictionary<string,MongoServer>();		 
	        }
            string uniqueId = Guid.NewGuid().ToString();
            _servers.TryAdd(uniqueId, MongoServer.Create(new MongoUrl(connectionString)));
            return uniqueId;
        }

        public static MongoServer GetServer(string key)
        {
            return _servers[key];
        }

        public static string GetConnectionString(string ip, string port = null)
        {
            if (string.IsNullOrEmpty(port))
            {
                return string.Format("mongodb://{0}:27017", ip);
            }
            else
            {
                return string.Format("mongodb://{0}:{1}", ip, port);
            }
        }

        public static string GetConnectionString(string user, string password, string ip, string port = null)
        {
            string p = string.IsNullOrEmpty(port) ? "27017" : port;

            return string.Format("mongodb://{0}:{1}@{2}:{3}",user,password,ip,port);
        }

        public static string GetConnectionString(string user, string password, string ip)
        {
            return string.Format("mongodb://{0}:{1}@{2}", user, password, ip);
        }
    }
}